package so.sao.shop.supplier.service.account.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import so.sao.shop.supplier.dao.AccountDao;
import so.sao.shop.supplier.dao.account.AfterSettingDao;
import so.sao.shop.supplier.domain.User;
import so.sao.shop.supplier.domain.account.AfterSetting;
import so.sao.shop.supplier.pojo.Result;
import so.sao.shop.supplier.service.account.AfterSettingService;

import java.util.Date;
/**
 * <p>Version: supplier V1.2.0 </p>
 * <p>Title: AfterSetting</p>
 * <p>Description: 供应商售后设置</p>
 *
 * @author: cris
 * @Date: Created in 2017/11/22 10:05
 */
@Service
public class AfterSettingServiceImpl implements AfterSettingService {

    @Autowired
    private AfterSettingDao afterSettingDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<AfterSetting> save(AfterSetting afterSetting) {
        //根据用户查询是否有售后地址存在
        AfterSetting as = afterSettingDao.findByUserIdOrParentId(afterSetting.getUserId(),afterSetting.getParentId());
        if(as != null && !as.getId().equals(afterSetting.getId())) {
            return Result.fail("退换货地址已经存在");
        }
        if(afterSetting.getId() != null){
            afterSetting.setUpdateTime(new Date());
            afterSettingDao.updateByPrimaryKey(afterSetting);
            return Result.success("退换货地址保存成功");
        }
        afterSettingDao.insertSelective(afterSetting);
        return Result.success("退换货地址保存成功");
    }

    @Override
    public Result<AfterSetting> get(Long userId, Long parentId) {
        AfterSetting afterSetting = afterSettingDao.findByUserIdOrParentId(userId,parentId);
        return Result.success("查询售后设置成功",afterSetting);
    }

    /**
     * 根据用户id- accountId : 264 - 查询售后设置
     * @param accountId
     * @return
     */
    @Override
    public AfterSetting getAfterSetting( Long accountId ) {
        User user = afterSettingDao.findParentIdAndUserIdByAccountId( accountId );
        AfterSetting afterSetting = afterSettingDao.findByUserIdOrParentId( user.getId(),user.getParentId() );
        return afterSetting;
    }
}
